package com.audi.handler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import android.os.Message;

import com.audi.message.ActionMessage;
import com.google.gson.Gson;

/**
 * @author PhongNT11
 * 
 */
public abstract class Handler implements ActionMessage {
	private Gson gson;

	/**
	 * 
	 */
	protected Handler() {
		gson = new Gson();
	}

	/**
	 * processMessage
	 * 
	 * @param actionId
	 *            int
	 * @param data
	 *            String
	 * @return Message
	 * @see message.arg1 = 0 if return successful, message.arg1 = -1 if fail
	 */
	public abstract Message process(int actionId, String data);

	/**
	 * convert json data to List 
	 * 
	 * @param <T>
	 * 
	 * @param data
	 *            String
	 * @return ArrayList DeviceItem
	 * @see get all device
	 */
	public <T> List<T> convertJson2List(String data, Class<T> tClass) {
		Type type = new ListParameterizedType(tClass);
        List<T> list = gson.fromJson(data, type);
        return list;
	}

	/**
	 * Convert data json to object 
	 * @param data
	 * @param classOfT
	 * @return
	 */
	public <T> T convertJson2Obj(String data, Class<T> classOfT) {
		return gson.fromJson(data, classOfT);
	}

	private class ListParameterizedType implements ParameterizedType {

		private Type type;

		private ListParameterizedType(Type type) {
			this.type = type;
		}

		@Override
		public Type[] getActualTypeArguments() {
			return new Type[] { type };
		}

		@Override
		public Type getRawType() {
			return ArrayList.class;
		}

		@Override
		public Type getOwnerType() {
			return null;
		}
	}

}
